package com.jrauto.CarAppBackend.controller;

/**
 * @author : huiMing
 * Date : 2025年09月11日 10:45
 * @version V1.0
 */

import com.jrauto.CarAppBackend.entity.ChatRoom;
import com.jrauto.CarAppBackend.entity.dto.ChatRoomDTO;
import com.jrauto.CarAppBackend.service.ChatRoomService;
import com.jrauto.CarAppBackend.utils.R;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * chat
 */
@Slf4j
@RestController
@RequestMapping("/chatroom")
@CrossOrigin(origins = "*")
public class ChatRoomController {

    @Resource
    private ChatRoomService chatRoomService;

    /**
     * 创建或获取聊天室
     */
    @PostMapping("/create")
    public R<ChatRoom> createChatRoom(@RequestParam @NotNull Integer buyerId,
                                           @RequestParam @NotNull Integer sellerId,
                                           @RequestParam @NotNull Integer carId) {
        try {
            ChatRoom chatRoom = chatRoomService.createOrGetChatRoom(buyerId, sellerId, carId);
            return R.ok("操作成功", chatRoom);
        } catch (Exception e) {
            log.error("创建聊天室失败：{}", e.getMessage(), e);
            return R.ok("创建聊天室失败");
        }
    }

    /**
     * 根据房间ID获取聊天室
     */
    @GetMapping("/{roomId}")
    public R<ChatRoom> getChatRoomById(@PathVariable Integer roomId) {
        try {
            ChatRoom chatRoom = chatRoomService.getChatRoomById(roomId);
            if (chatRoom == null) {
                return R.fail("聊天室不存在");
            }
            return R.ok(chatRoom);
        } catch (Exception e) {
            log.error("获取聊天室失败：{}", e.getMessage(), e);
            return R.fail("获取聊天室失败");
        }
    }

    /**
     * 获取用户的聊天室列表
     */
    @GetMapping("/user/{userId}")
    public R<List<ChatRoomDTO>> getUserChatRooms(@PathVariable Integer userId) {
        try {
            List<ChatRoomDTO> chatRooms = chatRoomService.getUserChatRooms(userId);
            return R.ok(chatRooms);
        } catch (Exception e) {
            log.error("获取用户聊天室列表失败：{}", e.getMessage(), e);
            return R.fail("获取聊天室列表失败");
        }
    }

    /**
     * 清零未读消息数
     */
    @PutMapping("/{roomId}/read")
    public R<Void> markRoomAsRead(@PathVariable Integer roomId,
                                       @RequestParam @NotNull Integer userId) {
        try {
            boolean success = chatRoomService.clearUnreadCount(roomId, userId);
            if (success) {
                return R.ok("操作成功");
            } else {
                return R.fail("操作失败");
            }
        } catch (Exception e) {
            log.error("标记聊天室已读失败：{}", e.getMessage(), e);
            return R.fail("操作失败");
        }
    }
}